using MediatR;
using WorkOrder.Domain;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 问诊单查询处理器
    /// </summary>
    public class ConsultationOrderHandler : IRequestHandler<ConsultationOrderQueryCommand, APIResult<ApiPaging<ConsultationOrder>>>
    {
        private readonly IBaseRepository<ConsultationOrder> _consultationRepository;

        public ConsultationOrderHandler(IBaseRepository<ConsultationOrder> consultationRepository)
        {
            _consultationRepository = consultationRepository;
        }

        public Task<APIResult<ApiPaging<ConsultationOrder>>> Handle(ConsultationOrderQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<ConsultationOrder>> result = new APIResult<ApiPaging<ConsultationOrder>>();
            result.Code = ApiEnum.Success;
            result.Msg = "查询成功";

            var list = _consultationRepository.GetAll().Where(c =>c.IsDelete== false);

            // 如果没有数据，生成测试数据
            if (!list.Any())
            {
                list = GenerateTestData().AsQueryable();
            }
            Console.WriteLine($"原始数据数量: {list.Count()}");
            // 按时间范围筛选
            if (request.Begin != null && request.End != null)
            {
                list = list.Where(a => a.SubmitTime >= request.Begin && a.SubmitTime <= request.End.Value.AddDays(1));
                Console.WriteLine($"按时间筛选后数量: {list.Count()}");
            }

            // 按订单状态筛选
            if (!string.IsNullOrEmpty(request.OrderStatus))
            {
                list = list.Where(a => a.OrderStatus == request.OrderStatus);
                Console.WriteLine($"按订单状态筛选后数量: {list.Count()}");
            }

            // 按问诊方式筛选
            if (!string.IsNullOrEmpty(request.ConsultationMethod))
            {
                list = list.Where(a => a.ConsultationMethod == request.ConsultationMethod);
                Console.WriteLine($"按问诊方式筛选后数量: {list.Count()}");
            }

            // 按患者姓名筛选
            if (!string.IsNullOrEmpty(request.PatientName))
            {
                list = list.Where(a => a.PatientName.Contains(request.PatientName));
                Console.WriteLine($"按患者姓名筛选后数量: {list.Count()}");
            }

            // 分页处理
            var totalCount = list.Count();
            var row = list.OrderByDescending(a => a.SubmitTime)
                         .Skip((request.PageIndex - 1) * request.PageSize)
                         .Take(request.PageSize)
                         .ToList();

            Console.WriteLine($"分页后数量: {row.Count()}, PageIndex: {request.PageIndex}, PageSize: {request.PageSize}");

            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            var page = new ApiPaging<ConsultationOrder>
            {
                Total = totalCount,
                TotalPage = totalPage,
                PageData = row
            };

            result.Data = page;
            return Task.FromResult(result);
        }

        /// <summary>
        /// 生成测试数据
        /// </summary>
        /// <returns></returns>
        private List<ConsultationOrder> GenerateTestData()
        {
            var testData = new List<ConsultationOrder>();
            var statuses = new[] { "待支付", "进行中", "已完成", "已取消", "已退诊" };
            var consultationMethods = new[] { "视频问诊", "电话问诊", "图文问诊", "极速电话", "复诊开药" };
            var consultationSources = new[] { "视频问诊", "电话问诊", "极速图文" };
            var departments = new[] { "内科", "外科", "儿科", "妇产科", "眼科", "皮肤科", "神经科" };
            var doctors = new[] { "张医生", "李医生", "王医生", "赵医生", "钱医生", "孙医生", "周医生" };
            var symptoms = new[] { "头痛", "发热", "咳嗽", "腹痛", "失眠", "皮疹", "胸闷" };

            for (int i = 1; i <= 30; i++)
            {
                var status = statuses[i % statuses.Length];
                var submitTime = DateTime.Now.AddDays(-i);

                var order = new ConsultationOrder
                {
                    OrderNumber = $"CON20240801{i:D6}",
                    OrderType = "问诊订单",
                    ConsultationMethod = consultationMethods[i % consultationMethods.Length],
                    ConsultationSource = consultationSources[i % consultationSources.Length],
                    OrderStatus = status,
                    TotalAmount = 100 + i * 20,
                    CouponAmount = i % 4 == 0 ? 20 : 0,
                    ActualPayment = 100 + i * 20 - (i % 4 == 0 ? 20 : 0),
                    ConsultationFee = 100 + i * 20,
                    CreateTime = submitTime,
                    PaymentMethod = status != "待支付" ? "微信支付" : null,
                    PaymentTime = status != "待支付" ? submitTime.AddMinutes(5) : null,
                    SubmitTime = submitTime,
                    PatientName = $"患者{i}",
                    PatientGender = i % 2 == 0 ? "男" : "女",
                    PatientAge = 20 + i % 60,
                    PatientPhone = $"1881234{i:D4}",
                    SymptomDescription = $"{symptoms[i % symptoms.Length]}，持续{i % 7 + 1}天",
                    MedicalHistory = i % 3 == 0 ? "有高血压病史" : "无特殊病史",
                    AppointmentTime = status == "进行中" ? DateTime.Now.AddHours(i % 24) : null,
                    SubmissionTime = submitTime,
                    DoctorName = doctors[i % doctors.Length],
                    Department = departments[i % departments.Length],
                    ConsultationStartTime = status == "已完成" ? submitTime.AddHours(1) : null,
                    CallDurationMinutes = status == "已完成" ? 15 + i % 30 : null,
                    PatientRating = status == "已完成" ? 4 + i % 2 : null,
                    PatientReview = status == "已完成" ? "医生很专业，解答详细" : null,
                    ConsultationEndTime = status == "已完成" ? submitTime.AddHours(1).AddMinutes(15 + i % 30) : null,
                    HasConsultationRecord = status == "已完成",
                    UserName = $"user{i}",
                    Remarks = i % 5 == 0 ? "患者要求加急处理" : ""
                };

                testData.Add(order);
            }

            return testData;
        }
    }
}
